package com.kun.goods.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.api.IGoodsNumberLogService;
import com.kun.api.IGoodsService;
import com.kun.common.constant.ShopCode;
import com.kun.common.exception.CustomerException;
import com.kun.goods.mapper.TradeGoodsMapper;
import com.kun.pojo.domain.TradeGoods;
import com.kun.pojo.domain.TradeGoodsNumberLog;
import com.kun.pojo.entity.Result;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.Date;


@Service
@DubboService(interfaceClass = IGoodsService.class)
public class TradeGoodsServiceImpl extends ServiceImpl<TradeGoodsMapper, TradeGoods> implements IGoodsService {

    @Autowired
    private IGoodsNumberLogService goodsNumberLogService;

    /*
     * 根据商品id查询
     * */
    @Override
    public TradeGoods findOne(Long goodsId) {
        if (goodsId == null) {
            throw new CustomerException(ShopCode.SHOP_REQUEST_PARAMETER_VALID);
        }
        return getById(goodsId);
    }

    /**
     * 扣减库存
     */
    @Override
    public Result reduceGoodsNum(@Valid TradeGoodsNumberLog tradeGoodsNumberLog) {
        TradeGoods tradeGoods = findOne(tradeGoodsNumberLog.getGoodsId());
        if (tradeGoods.getGoodsNumber() < tradeGoodsNumberLog.getGoodsNumber())
            // 商品扣减失败，库存不足
            throw new CustomerException(ShopCode.SHOP_GOODS_NUM_NOT_ENOUGH);

        // 减少库存
        lambdaUpdate().set(TradeGoods::getGoodsNumber,
                        tradeGoods.getGoodsNumber() - tradeGoodsNumberLog.getGoodsNumber())
                .eq(TradeGoods::getGoodsId, tradeGoods.getGoodsId()).update();

        // 记录日志
        tradeGoodsNumberLog.setGoodsNumber(-tradeGoodsNumberLog.getGoodsNumber());
        tradeGoodsNumberLog.setLogTime(new Date());
        goodsNumberLogService.save(tradeGoodsNumberLog);

        return Result.success(ShopCode.SHOP_SUCCESS.getMessage());
    }
}




